<template>
  <div>
    <div class="cer-tabs">
      <div class="cer-tabs-center">
        <div class="cer-tabs" :class="isActive?'active':''" @click="onClickactive(true)">账号登录</div>
        <div class="cer-tabs" :class="!isActive?'active':''" @click="onClickactive(false)">手动上传</div>
      </div>
    </div>

    <div v-if="isActive">
      <a-spin :spinning="submit" tip='登录中,请稍后...'>
        <div class="d-cerlogin">
          <div class="d-cerlogin-children">
            <div class="title">
              <h1>登录苹果开发者账号</h1>
            </div>
            <a-form layout="vertical" :model="formInline" @submit="onSubmitCer(formInline)">
              <a-form-item>
                <a-input v-model:value="formInline.name" placeholder="账号">
                  <template v-slot:prefix>
                    <UserOutlined style="color:rgba(0,0,0,.25)" />
                  </template>
                </a-input>
              </a-form-item>
              <a-form-item>
                <a-input v-model:value="formInline.pass" type="pass" placeholder="密码">
                  <template v-slot:prefix>
                    <LockOutlined style="color:rgba(0,0,0,.25)" />
                  </template>
                </a-input>
              </a-form-item>
              <div>
                <a-form-item>
                  <a-button type="primary" html-type="submit" :disabled="formInline.name === '' || formInline.pass === ''">
                    登录
                  </a-button>
                </a-form-item>
              </div>
            </a-form>
          </div>
        </div>
        <VerificationCode :codeVisible='codeVisible' @onCodeVisible='onCodeVisible' />
        <ChoosePhone :phoneVisible='phoneVisible' :phoneList='phoneList' @onPhoneVisible='onPhoneVisible' />
      </a-spin>
    </div>

    <div v-else>
      <a-spin tip="提交中,请稍后..." :spinning="submit">
        <div class="d-cer-p8">
          <a-form>
            <a-form-item label="开发者账号">
              <a-input v-model:value="modelRef.name" />
            </a-form-item>
            <a-form-item label="Issuer ID">
              <a-input v-model:value="modelRef.issuerid" />
            </a-form-item>
            <a-form-item label="密钥 ID">
              <a-input v-model:value="modelRef.keyid" />
            </a-form-item>
            <a-form-item label="API 密钥">
              <a-upload name="file" :beforeUpload="beforeUpload">
                <a-button>
                  <UploadOutlined /> 上传P8文件
                </a-button>
              </a-upload>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" :disabled="modelRef.name === '' || modelRef.issuerid === '' || modelRef.keyid==='' || files===''" @click="onClickUpload">
                提交
              </a-button>
            </a-form-item>
          </a-form>
        </div>
      </a-spin>
    </div>
  </div>

</template>

<script lang='ts'>
import { reactive, ref, toRefs } from "vue";
import { UploadOutlined } from "@/components/AntDesign/icons/icons";
import { $message } from "@/components/AntDesign/message";
import $router from "@/router";
import { addapiKeys, addP8cer } from "@/api/cerApi";
import { UserOutlined, LockOutlined } from "@/components/AntDesign/icons/icons";
import VerificationCode from "@/components/CerModule/CerUpload/childComponent/VerificationCode/Code.vue";
import ChoosePhone from "@/components/CerModule/CerUpload/childComponent/ChoosePhone/CellPhone.vue";
export default {
  components: {
    UploadOutlined,
    UserOutlined,
    LockOutlined,
    VerificationCode,
    ChoosePhone,
  },
  setup() {
    const submit = ref(false);
    const data = reactive({
      isActive: true,
      phoneVisible: false,
      codeVisible: false,
      phoneList: [],
      phonedata: [],
      SessionId: "",
      scnt: "",
      formInline: {
        name: "",
        pass: "",
      },
    } as any);

    const onClickactive = (active: boolean) => {
      data.isActive = active;
    };
    let phonedata: any = {};
    let device: boolean = false;
    const onSubmitCer = async (param: { name: string; pass: string }) => {
      try {
        submit.value = true;
        const result = await addapiKeys({ type: "login", ...param });
        submit.value = false;
        data.phonedata = result.data.data;
        data.SessionId = result.data.SessionId;
        data.scnt = result.data.scnt;

        if (result.data.code == 200) {
          $message("success", result.data.message);
          $router.push({ path: "/cerlist" });
        }

        if (result.data.code == 201) {
          data.codeVisible = true;
          phonedata = result.data.data[0];
        }

        if (result.data.code == 202) {
          result.data.data.forEach((element: any) => {
            data.phoneList.push(element.obfuscatedNumber);
          });
          data.phoneVisible = true;
        }

        if (result.data.code == 203) {
          data.codeVisible = true;
          device = true;
        }
      } catch (error) {
        submit.value = false;
        console.log(error);
        $message("error", "执行错误");
      }
    };

    const onPhoneVisible = async (index: number) => {
      submit.value = true;
      data.phoneVisible = false;
      data.phoneList = [];
      phonedata = data.phonedata[index - 1];
      phonedata.SessionId = data.SessionId;
      phonedata.scnt = data.scnt;
      try {
        const result = await addapiKeys({
          ...data.formInline,
          type: "phone",
          data: phonedata,
        });
        submit.value = false;
        if (result.data.code == 200) {
          data.codeVisible = true;
        }
      } catch (error) {
        submit.value = false;
        console.log(error);
        $message("error", "执行错误");
      }
    };

    const onCodeVisible = async (code: number) => {
      try {
        submit.value = true;
        data.codeVisible = false;
        if (device) {
          phonedata.cdata = { securityCode: { code } };
        } else {
          phonedata.cdata = {
            securityCode: { code },
            phoneNumber: { id: phonedata.id },
            mode: phonedata.pushMode,
          };
        }
        phonedata.SessionId = data.SessionId;
        phonedata.scnt = data.scnt;

        const result = await addapiKeys({
          type: "code",
          data: phonedata,
          ...data.formInline,
        });
        submit.value = false;
        if (result.data.code == 200) {
          $message("success", result.data.message);
          $router.push({ path: "/cerlist" });
        } else {
          $message("error", result.data.message);
        }
      } catch (error) {
        submit.value = false;
        console.log(error);
        $message("error", "执行错误");
      }
    };

    // ==============================================================
    // ==============================================================
    // ==============================================================

    const modelRef = reactive({
      name: "",
      issuerid: "",
      keyid: "",
    });

    /* 上传回调 */
    const files = ref<any>("");
    let P8file: any = null;
    function beforeUpload(file: any) {
      files.value = file;
      P8file = file;
      return false;
    }

    async function onClickUpload() {
      submit.value = true;
      if (/p8$/.test(files.value.name)) {
        const formData: FormData = new FormData();
        formData.append("file", P8file);
        formData.append("name", modelRef.name);
        formData.append("issuerid", modelRef.issuerid);
        formData.append("keyid", modelRef.keyid);
        try {
          const result = await addP8cer(formData);
          submit.value = false;
          $message("success", result.data.message);
          $router.push({ path: "/cerlist" });
        } catch (error) {
          submit.value = false;
          $message("error", error.data.message || "执行错误");
        }
      } else {
        submit.value = false;
        $message("error", "请上传正确的API密钥文件");
      }
    }

    return {
      ...toRefs(data),
      files,
      submit,
      modelRef,
      beforeUpload,
      onClickUpload,
      onClickactive,
      onSubmitCer,
      onPhoneVisible,
      onCodeVisible,
    };
  },
};
</script>
<style lang="less" scoped>
.d-cer-p8 {
  width: 20%;
  margin: 0 auto;
  .ant-btn,
  .ant-input {
    width: 100%;
    height: 40px;
    border-radius: 4px;
  }
}
.cer-tabs {
  width: 100%;
  .cer-tabs-center {
    width: 30%;
    margin: 0 auto;
    margin-bottom: 40px;
    height: 50px;
    display: flex;
    line-height: 50px;
    text-align: center;
    .cer-tabs {
      width: 20%;
      margin: 0 auto;
      cursor: pointer;
    }
    .cer-tabs:hover {
      border-bottom: 3px solid#1890FF;
      color: #359fec;
    }
    .active {
      border-bottom: 3px solid#1890FF;
      color: #359fec;
    }
  }
}
.d-cerlogin {
  text-align: center;
  width: 40%;
  margin: 0 auto;
  padding: 20px;
  height: 330px;
  .d-cerlogin-children {
    width: 330px;
    margin: 0 auto;
    position: relative;
    top: 50%;
    margin-top: -176px;
    .title h1 {
      font-weight: bold;
      font-size: 20px;
      margin: 25px 0;
    }
    .ant-btn {
      width: 100%;
      height: 40px;
      border-radius: 4px;
    }
  }
}
.ant-form-vertical .ant-form-item {
  padding-bottom: 0px;
}
</style>